
package com.example.demo.controller;


import com.example.common.util.R;
import com.example.demo.filter.JwtTokenUtils;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * auth
 *
 * @author wfnuser
 */
@RestController("auth")
@RequestMapping("/v1/auth")
@AllArgsConstructor
public class AuthController {

    private JwtTokenUtils jwtTokenUtils;
    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;

    /**
     * Whether the Nacos is in broken states or not, and cannot recover except by being restarted
     *
     * @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code equal to 500 indicates that
     * Nacos is in broken states.
     */

    @PostMapping("login")
    public R<String> login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) {

        // 通过用户名和密码创建一个 Authentication 认证对象，实现类为 UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        R<String> rr = new R<String>();

        //通过 AuthenticationManager（默认实现为ProviderManager）的authenticate方法验证 Authentication 对象
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //将 Authentication 绑定到 SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成Token
        String token = jwtTokenUtils.createToken(authentication);
        rr.setCode(200);
        rr.setData("Bearer " + token);
        return rr;
    }

//    @PutMapping("password")
//    public R<String> updatePassword(@RequestParam(value = "oldPassword") String oldPassword,
//                                             @RequestParam(value = "newPassword") String newPassword) {
//
//        R<String> rr = new R<String>();
//        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String username = ((UserDetails) principal).getUsername();
//        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//        String password = userDetails.getPassword();
//
//        // TODO: throw out more fine grained exceptions
//        try {
//            if (PasswordEncoderUtil.matches(oldPassword, password)) {
//                userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword));
//                rr.setCode(200);
//                rr.setMsg("Update password success");
//            } else {
//                rr.setCode(401);
//                rr.setMsg("Old password is invalid");
//            }
//        } catch (Exception e) {
//            rr.setCode(500);
//            rr.setMsg("Update userpassword failed");
//        }
//        return rr;
//    }
}
